import puppeteer, { LaunchOptions } from 'puppeteer';
import * as path from 'path';
import * as fs from 'fs';
import { fetchNewAts } from './tool/at';
import { createComment, getLatestCommentTimestamp } from './post/create';
import { fetchNote } from './tool/note';

const lauchOptions: LaunchOptions = {
    channel: undefined,
    executablePath: undefined,
    ignoreDefaultArgs: false,
    enableExtensions: false,
    handleSIGINT: true,
    handleSIGTERM: true,
    handleSIGHUP: true,
    timeout: 0,
    dumpio: undefined,
    env: undefined,
    pipe: undefined,
    browser: undefined,
    extraPrefsFirefox: undefined,
    waitForInitialPage: undefined,
    headless: false,
    userDataDir: path.join(process.cwd(), 'browser-data'),
    devtools: false,
    debuggingPort: undefined,
    args: undefined,

    // ConnectOptions
    acceptInsecureCerts: undefined,
    networkEnabled: undefined,
    downloadBehavior: undefined,
    slowMo: undefined,
    targetFilter: undefined,
    protocol: undefined,
    protocolTimeout: undefined,
    browserWSEndpoint: undefined,
    browserURL: undefined,
    transport: undefined,
    headers: undefined,
    capabilities: undefined
};


(async () => {
    const browser = await puppeteer.launch(lauchOptions);
    const viewPort = {
        width: 1080,
        height: 3840,
    };

    const page = await browser.newPage();
    await page.setViewport(viewPort);

    const timestamp = Date.now();
    const tempPath = path.join(process.cwd(), 'temp', `${timestamp}`);
    if (!fs.existsSync(tempPath)) {
        fs.mkdirSync(tempPath, { recursive: true });
    }

    while (true) {
        const latestAtTimestamp = await getLatestCommentTimestamp();
        console.log("latestAtTimestamp: ", latestAtTimestamp);

        const ats = await fetchNewAts(page);
        const newAts = ats.filter(at => {
            // console.log("at.timestamp(): ", at.timestamp(), " latestAtTimestamp: ", latestAtTimestamp);
            return at.timestamp() > latestAtTimestamp;
        });
        console.log("newAts: ", newAts.length);

        for (const at of newAts) {
            const newPage = await browser.newPage();
            await newPage.setViewport(viewPort);
            const note = await fetchNote(newPage, at.BV(), at.commentId());
            if (!note) {
                console.error(`note not found for at ${at.BV()} ${at.commentId()}`);
                continue;
            }
            const ok = await createComment(at, note);
            if (!ok) {
                console.error(`create comment failed for at ${at.BV()} ${at.commentId()}`);
                continue;
            }
            await newPage.close();
            console.log("note found for BV: ", at.BV(), " commentId: ", at.commentId(), " length: ", note.noteImages.length);
            await new Promise(resolve => setTimeout(resolve, 3000));
        }

        const random0to30 = Math.floor(Math.random() * 30);
        await new Promise(resolve => setTimeout(resolve, (30 + random0to30) * 1000));
    }

})();
